<!--
 * @Description:
 * @Author: lucl
 * @Date: 2021-06-22 14:46:30
 * @LastEditors: lucl
 * @LastEditTime: 2021-06-26 20:50:48
-->
<template>
  <div class="product-list">
    <!-- 添加按钮、模糊搜索、查询按钮 -->
    <div class="search">
      <div>

        <el-button class="btn" type="primary" @click="toAdd">添加</el-button>

      </div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="searchForm.name" clearable placeholder="产品名称" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" clearable placeholder="产品状态">
            <el-option label="正常" value="正常" />
            <el-option label="下架" value="下架" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.productCategoryId" clearable placeholder="产品分类">
            <el-option v-for="item in categoryData" :key="item.id" :label="item.name" :value="item.id" />
            <!-- <el-option label="下架" value="下架"></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="toSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格展示数据 -->
    <div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column
          type="index"
          label="序号"
        />
        <el-table-column
          prop="id"
          label="产品编号"
        />
        <el-table-column
          prop="name"
          label="名称"
        />
        <el-table-column
          label="图片"
          align="center"
          width="50px"
        >
          <template slot-scope="scope">
            <!-- scope是当前temlate模板的作用域对象 -->
            <!-- <img :src="scope.row.photo" alt=""> -->
            <el-image
              style="width: 30px; height: 30px"
              :src="scope.row.photo"
              :preview-src-list="[scope.row.photo]"
            />
          </template>

        </el-table-column>
        <el-table-column
          prop="price"
          label="价格"
          align="center"
        />
        <el-table-column
          label="状态"
        >
          <template slot-scope="scope">

            <!-- <el-tag v-if="scope.row.status==='正常'" type="success">{{scope.row.status}}</el-tag>
          <el-tag v-else type="danger">{{scope.row.status}}</el-tag> -->
            <el-tag :type="scope.row.status==='正常'?'success':'danger'">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="category.name"
          label="所属栏目"
        />
        <el-table-column
          label="操作"
          width="100"
        >
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleClick(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.status==='正常'" type="text" size="small" @click="ChangStatus(scope.row)">下架</el-button>
            <el-button v-else type="text" size="small" @click="ChangStatus(scope.row)">上架</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="pagination-div">
      <el-pagination
        :current-page="params.page"
        :page-sizes="[2,5,10,15,20]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 模态框 -->
    <!-- :before-close="reset" -->
    <el-dialog :title="title" :visible.sync="visible" @close="reset">
      <!-- {{form}} -->
      <el-form ref="ruleForm" :rules="rules" :model="form">
        <el-form-item prop="name" label="产品名称" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="productCategoryId" label="所属栏目" :label-width="formLabelWidth">
          <el-select v-model="form.productCategoryId" placeholder="请选择所属栏目">
            <el-option v-for="item in categoryData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="price" label="价格" :label-width="formLabelWidth">
          <el-input v-model.number="form.price" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="photo" label="封面" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"

            :action="uploadFileURL"

            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>

        </el-form-item>
        <el-form-item label="产品描述" :label-width="formLabelWidth">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
          />

        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible=false">取 消</el-button>
        <el-button type="primary" @click="tosave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageQuery } from '@/api/proCategory'
import { showFileURL, uploadFileURL } from '@/utils/config'
// 重命名
import { pageQuery as pageQueryPro } from '@/api/product'
import { saveOrUpdate } from '@/api/product'
export default {
  data() {
    return {
      // 校验规则{
      rules: {
        name: [
          {
            required: true,
            message: '请输入产品名称',
            trigger: 'blur'
          }
        ],
        price: [
          {
            required: true,
            message: '请输入产品价格',
            trigger: 'change'
          },
          {
            type: 'number',
            message: '请输入数值类型的价格',
            trigger: 'blur'

          }
        ],
        productCategoryId: [
          {
            required: true,
            message: '请选择所属栏目',
            trigger: 'change'
          }
        ],
        photo: [
          {
            required: true,
            message: '请填入图片',
            trigger: 'change'
          }
        ]
      },

      showFileURL,
      uploadFileURL,
      imageUrl: '',
      // 模态框的标题
      title: '',
      // 表单数据
      form: {},
      formLabelWidth: '80px',
      // 模态框的显示与隐藏
      visible: false,
      loading: false,
      // 表格展示数据
      tableData: [],
      params: {
        page: 1,
        pageSize: 10
      },
      // 总条数
      total: 0,
      // 产品栏目的数据,页面上来，就发送请求，请求所有的产品栏目数据，设置到categoryData.
      categoryData: [],
      // 模糊搜索表单的数据
      searchForm: {
        name: '',
        status: '',
        productCategoryId: ''
      }
    }
  },
  computed: {},
  watch: {
    // 深度监听分页参数
    params: {
      handler() {
        this.queryData()
      },
      deep: true
    }
  },
  created() {
    //   发请求
    this.queryCategoryData()
    this.queryData()
  },
  mounted() {},
  methods: {
    // 重置rule表单验证
    reset() {
      // 重置表单验证
      this.$refs.ruleForm.resetFields()
      this.form = {}
      this.imageUrl = ''
      // 超时调用,在多少毫秒后执行函数，
      // setTimeout(()=>{
      // this.visible = false;
      // },500);
    },
    //   改变状态信息
    async ChangStatus(res) {
      this.form = {
        ...res
      }
      this.form.status = (this.form.status === '正常' ? '下架' : '正常')
      const response = await saveOrUpdate(this.form)
      this.$notify.success({
        title: '成功',
        message: response.message
      })
      this.queryData()
    },
    //   编辑产品信息
    handleClick(res) {
      this.title = '编辑产品信息'
      console.log(res)
      this.form = {
        ...res
      }
      this.imageUrl = this.form.photo
      this.visible = true
    },
    //   新增保存信息  模态框确定按钮处理程序
    tosave() {
      // 获取dom的值，对值进行校验
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          console.log('校验通过')
          const res = await saveOrUpdate(this.form)
          this.queryData()
          this.visible = false
          this.$notify.success({
            title: '成功',
            message: res.message
          })
          // this.reset();
        } else {
          // 校验不通过
          return false
        }
      })
    },
    //   图片上传回调函数
    handleAvatarSuccess(res, file) {
      console.log('res', '图片上传成功后的res')
      this.imageUrl = URL.createObjectURL(file.raw)
      console.log(this.imageUrl)
      this.form.photo = showFileURL + res.data.id
    },
    //   图片上传之前回调函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    //   添加按钮处理事件
    toAdd() {
      this.queryCategoryData()
      // 清空表单数据
      this.form = {}
      this.imageUrl = ''

      this.title = '添加产品信息'
      this.visible = true
    },

    //   每页显示的条数法僧变化时的事件处理程序
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.params.pageSize = val
      this.params.page = 1
    },
    //   当前页码发生变化时，事件处理程序
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.params.page = val
    },
    //   查询按钮点击事件处理程序
    toSearch() {
      this.queryData()
    },
    //   获取产品分类数据
    async queryCategoryData() {
      const res = await pageQuery({ page: 1, pageSize: 100 })
      this.categoryData = res.data.list
    },
    // 分页模糊获取产品数据
    async queryData() {
      this.loading = true
      // 处理数据
      const temp = {
        ...this.params,
        ...this.searchForm
      }
      // 删除属性
      // 遍历对象
      for (const key in temp) {
        // key是属性名  temp[key]属性值
        // console.log(key,temp[key]);
        if (!temp[key]) {
          delete temp[key]
        }
      }

      const res = await pageQueryPro(temp)
      this.loading = false
      this.tableData = res.data.list
      this.total = res.data.total
    }

  }
}
</script>
<style lang="scss" scoped>
.product-list{
    padding: 10px;
}
.search{
    /* scc less css 预处理器 */

    display: flex;
    // height: 40px;
    .btn{
        margin-right: 10px;
    }
}

</style>
